package valuecomusa.fijibus.eticket.shorthaul;


import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
//import android.nfc.NfcAdapter;
import android.os.*;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import com.valuecomusa.bmf.NfcCardInfo;
import org.kobjects.base64.Base64;
import valuecomusa.fijibus.eticket.*;
import valuecomusa.fijibus.eticket.db.shorthaul.BusinessDBHandler;
import valuecomusa.fijibus.eticket.db.shorthaul.GpsDBHandler;
import valuecomusa.fijibus.eticket.dialog.CheckInV2_Stage_SelectMore;
import valuecomusa.fijibus.eticket.dialog.checkin_topup;
import valuecomusa.fijibus.eticket.dto.GpsCurrentLocationValue;
import valuecomusa.fijibus.eticket.dto.StagesOfRouteValue;
import valuecomusa.fijibus.eticket.ws.MemberValue;
import valuecomusa.fijibus.eticket.ws.PassengerTypeValue;
import valuecomusa.fijibus.eticket.ws.TransactionValue;
import valuecomusa.fijibus.eticket.ws.VoucherValue;

import java.io.File;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class CheckInV2Stage extends SunbeamActivity
{
    private static int counter = 1;
    private String TAG = "CheckInV2Stage";
    //--
    private StagesOfRouteValue currentLocation;
    private RadioGroup adult;
    private RadioGroup senior;
    private RadioGroup child;
    private RadioGroup disabled;
    private RadioGroup student;

    private int passengerCount = 0;
    private double Amount;
    private double xStageFare;
    private int stageCount;
    //--
    private double minFare;

    private TextView totalAmountTextView;
    private TextView stageCountTextView;

    private BusinessDBHandler db;
    private GpsDBHandler gpsDb;

//	private NfcAdapter nfcAdapter;
//	private PendingIntent mPendingIntent;

    private List<PassengerTypeValue> passengerTypeList;
    //--
    private ProgressDialog progress;
    //--
    private int[] stageButtonActive;

    public CheckInV2Stage()
    {
        TAG = TAG + "." + counter++;
        if (counter > 1000000)
            counter = 1;
    }

    private void RegisterStageButtonEvent()
    {
        stageButtonActive = new int[8];
        Arrays.fill(stageButtonActive, 0);
        //--
        int stageCount = db.getStageCountOfRoute(WorkingSession.getInstance().journalRoute.ISN);
        //--
        if (stageCount > 7)
        {
            ((Button) findViewById(R.id.checkin_stage_7)).setText("More...");
        }
        //--
        OnClickListener onClick = new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Button button = (Button) v;
                String text = button.getText().toString();
                Log.d(TAG, "Click on " + text);
                //--
                int idx = -1;
                if (text.toLowerCase().equals("tap out"))
                    idx = 0;
                if (text.toLowerCase().equals("more..."))
                    idx = 7;
                else
                    idx = Integer.parseInt(text.substring(0, 1));
                //--
                if (stageButtonActive[idx] == 0)
                {
                    for (int i = 0; i < stageButtonActive.length; i++)
                    {
                        if (stageButtonActive[i] == 1) //current selected
                        {
                            int id = Utilities.getResId("checkin_stage_" + i,
                                                        CheckInV2Stage.this,
                                                        R.id.class);
                            if (id > -1)
                            {
                                ((Button) findViewById(id)).setBackground(
                                        CheckInV2Stage.this.getResources().getDrawable(
                                                R.drawable.stage_text_button_states
                                                                                      )
                                                                         );
                                stageButtonActive[i] = 0;
                            }
                        }
                    }
                    //-- process logic
                    //-- recalculate fare
                    //-- open popup full stage if click More...
                    if (text.toLowerCase().equals("more..."))
                    {
                        Intent runActivity = new Intent(CheckInV2Stage.this, CheckInV2_Stage_SelectMore.class);
                        startActivityForResult(runActivity, Declarations.REQUEST_CHECK_IN_STAGE_MORE);
                        return;
                    }

                    button.setBackground(
                            CheckInV2Stage.this.getResources().getDrawable(
                                    R.drawable.stage_text_button_states2
                                                                          )
                                        );

                    stageButtonActive[idx] = 1;
                    //--
                    GetFareV2(idx);
                    CalcTotalAmount();
                }
            }
        };
        Button button = (Button) findViewById(R.id.checkin_stage_0);
        button.setOnClickListener(onClick);
        //--
        button = (Button) findViewById(R.id.checkin_stage_1);
        button.setOnClickListener(onClick);
        //--
        button = (Button) findViewById(R.id.checkin_stage_2);
        button.setOnClickListener(onClick);
        //--
        button = (Button) findViewById(R.id.checkin_stage_3);
        button.setOnClickListener(onClick);
        //--
        button = (Button) findViewById(R.id.checkin_stage_4);
        button.setOnClickListener(onClick);
        //--
        button = (Button) findViewById(R.id.checkin_stage_5);
        button.setOnClickListener(onClick);
        //--
        button = (Button) findViewById(R.id.checkin_stage_6);
        button.setOnClickListener(onClick);
        //--
        button = (Button) findViewById(R.id.checkin_stage_7);
        button.setOnClickListener(onClick);

    }

    public int getPassengerCount(RadioGroup g)
    {
        if (g == null)
            return 0;

        int selected = g.getCheckedRadioButtonId();
        if (selected < 0)
            return 0;

        RadioButton b = (RadioButton) findViewById(selected);

        return Integer.parseInt(b.getText().toString());
    }

    private double GetPassengerTypeDiscount(String type)
    {
        for (PassengerTypeValue xx : this.passengerTypeList)
        {
            if (xx.Type.toLowerCase().equals(type.toLowerCase()))
                return xx.Discount / 100;
        }
        return 0;
    }

    public void CalcTotalAmount()
    {
        int tmpNoOf = 0;
        try
        {
            Amount = 0;
            passengerCount = 0;
            //double discount = 0;
            //--
            tmpNoOf = getPassengerCount(adult);
            Amount = tmpNoOf * xStageFare * (1 - GetPassengerTypeDiscount("adult"));
            passengerCount = tmpNoOf;
            //--
            tmpNoOf = getPassengerCount(senior);
            Amount += tmpNoOf * xStageFare * (1 - GetPassengerTypeDiscount("senior"));
            passengerCount += tmpNoOf;
            //--
            tmpNoOf = getPassengerCount(child);
            Amount += tmpNoOf * xStageFare * (1 - GetPassengerTypeDiscount("child"));
            passengerCount += tmpNoOf;
            //--
            tmpNoOf = getPassengerCount(disabled);
            Amount += tmpNoOf * xStageFare * (1 - GetPassengerTypeDiscount("disabled"));
            passengerCount += tmpNoOf;
            //--
            tmpNoOf = getPassengerCount(student);
            Amount += tmpNoOf * xStageFare * (1 - GetPassengerTypeDiscount("student"));
            passengerCount += tmpNoOf;
            //--
            totalAmountTextView.setText(String.valueOf(WorkingSession.getInstance().RoundMoney(Amount)));
            stageCountTextView.setText(String.valueOf(stageCount));
        }
        catch (Exception ex)
        {
            Log.e(TAG, ex.getMessage());
        }
    }

    private void Initialize()
    {
//		nfcAdapter = NfcAdapter.getDefaultAdapter(this);
//		mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
//				getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        //--
        currentLocation = null;
        passengerCount = 0;
        Amount = 0;
        xStageFare = 0;
        stageCount = 1;
        passengerTypeList = null;
        //--
        db = new BusinessDBHandler(CheckInV2Stage.this);
        gpsDb = new GpsDBHandler(CheckInV2Stage.this);
        //--
        totalAmountTextView = (TextView) findViewById(R.id.check_in_stage_total_fare_text);
        stageCountTextView = (TextView) findViewById(R.id.checkin_text_stage_count);
        //printReceipt = (CheckBox) findViewById(R.id.chkPrintReceipt);
        //---
        adult = (RadioGroup) findViewById(R.id.Adult);
        senior = (RadioGroup) findViewById(R.id.Senior);
        child = (RadioGroup) findViewById(R.id.Child);
        disabled = (RadioGroup) findViewById(R.id.Disabled);
        //exempt = (RadioGroup) findViewById(R.id.Exempt);
        student = (RadioGroup) findViewById(R.id.Student);
        //--
        processing = false;
    }

    private void DisplayPassengerAndSelectHimType()
    {
        TextView x = (TextView) findViewById(R.id.tvCustID);
        x.setText(WorkingSession.getInstance().currentPassenger.UserName + " ("
                          + WorkingSession.getInstance().currentPassenger.getFullName() + ")");

        totalAmountTextView.setText(String.valueOf(WorkingSession.getInstance().RoundMoney(Amount)));
        //--
        x = (TextView) findViewById(R.id.checkin_text_current_balance);
        x.setText(WorkingSession.getInstance().decimalFormat.format(
                WorkingSession.getInstance().currentPassenger.CurrentBalance));
        //--
        x = (TextView) findViewById(R.id.checkin_text_stage_count);
        x.setText(String.valueOf(stageCount));
        //--
        if (WorkingSession.getInstance().currentPassenger.Picture != null &&
                WorkingSession.getInstance().currentPassenger.Picture.length() > 0)
        {
            try
            {
                byte[] imageData = Base64.decode(WorkingSession.getInstance().currentPassenger.Picture);
                Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
                String filePath = Utilities.SaveBitmapToSdCard(
                        CheckInV2Stage.this,
                        bitmap,
                        WorkingSession.getInstance().currentPassenger.ISN + ".jpg");

                ImageView memberImage = (ImageView) findViewById(R.id.checkin_member_image);
                memberImage.setImageBitmap(BitmapFactory.decodeFile(filePath));
            }
            catch (Exception ex)
            {
                Log.e(TAG, "[MemberImage] " + ex.getMessage());
            }
        }

        if (WorkingSession.getInstance().currentPassenger.PassengerType.toLowerCase().equals("adult"))
            adult.check(R.id.Adult1);
        else if (WorkingSession.getInstance().currentPassenger.PassengerType.toLowerCase().equals("senior"))
            senior.check(R.id.Senior1);
        else if (WorkingSession.getInstance().currentPassenger.PassengerType.toLowerCase().equals("child"))
            child.check(R.id.Child1);
        else if (WorkingSession.getInstance().currentPassenger.PassengerType.toLowerCase().equals("disabled"))
            disabled.check(R.id.Disabled1);
        /*else if (WorkingSession.getInstance().currentPassenger.PassengerType.toLowerCase().equals("exempt"))
            exempt.check(R.id.Exempt1);*/
        else if (WorkingSession.getInstance().currentPassenger.PassengerType.toLowerCase().equals("student"))
            student.check(R.id.Student1);
    }

	/*private void showStageButton()
    {
		RadioGroup stageGroup1 = (RadioGroup) findViewById(R.id.stageGroup1);
		RadioGroup stageGroup2 = (RadioGroup) findViewById(R.id.stageGroup2);

		int xCount = db.getStageCountOfRoute(WorkingSession.getInstance().journalRoute.ISN);
		if (xCount <= 0)
		{
			stageGroup1.setVisibility(View.GONE);
			stageGroup2.setVisibility(View.GONE);
			return;
		}
		if (xCount < 4)
		{
			stageGroup2.setVisibility(View.GONE);
			if (xCount < 3)
				findViewById(R.id.checkin_btStage3).setVisibility(View.GONE);
			if (xCount < 2)
				findViewById(R.id.checkin_btStage2).setVisibility(View.GONE);
		}
		else
		{
			if (xCount < 7)
				findViewById(R.id.checkin_btStage7).setVisibility(View.GONE);
			if (xCount < 6)
				findViewById(R.id.checkin_btStage6).setVisibility(View.GONE);
			if (xCount < 5)
				findViewById(R.id.checkin_btStage5).setVisibility(View.GONE);
		}
	}*/

    private void showStageButtonV2()
    {
        LinearLayout group1 = (LinearLayout) findViewById(R.id.checkin_stage_group_1);
        LinearLayout group2 = (LinearLayout) findViewById(R.id.checkin_stage_group_2);

        int xCount = db.getStageCountOfRoute(WorkingSession.getInstance().journalRoute.ISN);
        if (xCount <= 0)
        {
            group1.setVisibility(View.GONE);
            group2.setVisibility(View.GONE);
            return;
        }
        if (xCount < 4)
        {
            group2.setVisibility(View.GONE);
            if (xCount < 3)
                findViewById(R.id.checkin_stage_3).setVisibility(View.GONE);
            if (xCount < 2)
                findViewById(R.id.checkin_stage_2).setVisibility(View.GONE);
        }
        else
        {
            if (xCount < 7)
                findViewById(R.id.checkin_stage_7).setVisibility(View.GONE);
            if (xCount < 6)
                findViewById(R.id.checkin_stage_6).setVisibility(View.GONE);
            if (xCount < 5)
                findViewById(R.id.checkin_stage_5).setVisibility(View.GONE);
        }
        //select stage 1 by default
        findViewById(R.id.checkin_stage_1).performClick();
    }

    private ThreadHandlerCheckCardIntoCardReader cardIntoCardReader;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate...");
        // --

        setContentView(R.layout.check_in_v2_stage);
        WorkingSession.getInstance().currentActivity = CheckInV2Stage.this;

        // --
        doCommon();
        HandlerThread threadHandlerCard = new HandlerThread("ThreadHandlerCheckCardIntoCardReader");
        threadHandlerCard.start();
        cardIntoCardReader = new ThreadHandlerCheckCardIntoCardReader(threadHandlerCard.getLooper());
        Initialize();
        //--
        progress = new ProgressDialog(this);
        progress.setMessage("Waiting...");
        progress.setCancelable(false);
        //--
        HandlerThread uiThread = new HandlerThread("UIThreadHandler");//to prepare a looper
        uiThread.start();
        uiThreadHandler = new UIThreadHandler(uiThread.getLooper()); //to process UI such as AlertDialog,...
        //--
        minFare = db.getStageFare(WorkingSession.getInstance().journalRoute.ISN, 1);
        //--
        passengerTypeList = db.getPassengerType();
        if (passengerTypeList == null || passengerTypeList.size() == 0)
        {
            Log.d(TAG, "Could not get Passenger Type discount");
            WorkingSession.getInstance().ShowToast(this,
                                                   "Could not get Passenger Type's discount",
                                                   Toast.LENGTH_LONG);
            return;
        }
        //--
        List<StagesOfRouteValue> stageList = db.getStagesOfRoute(WorkingSession.getInstance().journalRoute.ISN);
        ArrayAdapter<StagesOfRouteValue> stages = new ArrayAdapter<StagesOfRouteValue>(this,
                                                                                       android.R.layout.simple_dropdown_item_1line, stageList);
        //---
        Spinner xx = (Spinner) findViewById(R.id.checkin_current_location);
        xx.setAdapter(stages);
        xx.setOnItemSelectedListener(currentLocationItemClick);
        //---
        Button xxClick = (Button) findViewById(R.id.checkin_current_location_click);
        xxClick.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Spinner xx = (Spinner) findViewById(R.id.checkin_current_location);
                xx.performClick();
            }
        });
        //--
        RegisterStageButtonEvent();
        showStageButtonV2();
        RegisterPassengerAndPayByEvent();
        //--
        findViewById(R.id.checkin_stage_0).setEnabled(false);
        //--
        DisplayPassengerAndSelectHimType();

        //---
		/*if (xStageFare < 0)
		{
			WorkingSession.getInstance().ShowToast(this, "Could not get Fare", Toast.LENGTH_LONG);
		}*/
        //--
        GpsCurrentLocationValue currentGpsLocation = gpsDb.getCurrentLocation(
                WorkingSession.getInstance().setupJournal.ISN);
        if (currentGpsLocation != null)
        {
            Log.d(TAG, String.format("Current location: %d", currentGpsLocation.ClosestStage));
            int idx = -1;
            for (int i = 0; i < stageList.size(); i++)
            {
                Log.d(TAG, String.format("Stage: %d", stageList.get(i).StageISN));
                if (stageList.get(i).StageISN == currentGpsLocation.ClosestStage &&
                        stageList.get(i).BusStationISN == currentGpsLocation.ClosestBusStation)
                {
                    idx = i;
                    break;
                }
            }
            if (idx != -1)
                xx.setSelection(idx);
        }
        //-- play bula voice
        //Utilities.PlayMedia(CheckInV2Stage.this, "bula.mp3");
        //---
        CheckBalanceAndNotify();
    }

    private AdapterView.OnItemSelectedListener currentLocationItemClick = new AdapterView.OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long rowId)
        {
            StagesOfRouteValue sel = (StagesOfRouteValue) parent.getItemAtPosition(position);

            Log.d(TAG, String.format("Select location: %d - %s", sel.StageISN, sel.StationName));
            currentLocation = sel;
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView)
        {
            currentLocation = null;
        }
    };

    private void RegisterPassengerAndPayByEvent()
    {
        //--
        adult.setOnCheckedChangeListener(onPassengerCheckedChange);
        senior.setOnCheckedChangeListener(onPassengerCheckedChange);
        child.setOnCheckedChangeListener(onPassengerCheckedChange);
        disabled.setOnCheckedChangeListener(onPassengerCheckedChange);
        //exempt.setOnCheckedChangeListener(onPassengerCheckedChange);
        student.setOnCheckedChangeListener(onPassengerCheckedChange);
        //---
        Button payAccount = (Button) findViewById(R.id.check_in_stage_bmf);
        payAccount.setOnClickListener(onPaybyBMF);
        //--
        Button cash_topup = (Button) findViewById(R.id.check_in_stage_cash_topup);
        cash_topup.setOnClickListener(onCashAndTopUpClick);
        //--
        Button cancel = (Button) findViewById(R.id.check_in_stage_cancel);
        cancel.setOnClickListener(onCancelClick);
    }

    private MediaPlayer errorVoice;

    private void CheckBalanceAndNotify()
    {
        if (WorkingSession.getInstance().currentPassenger.CurrentBalance < 0)
        {
            errorVoice = Utilities.PlayMedia(CheckInV2Stage.this, "insufficient-balance.mp3");
            //--
            TextView balanceText = (TextView) findViewById(R.id.checkin_text_current_balance);
            balanceText.setTextColor(Color.RED);
            //--
            Button button = (Button) findViewById(R.id.check_in_stage_bmf);
            button.setEnabled(false);
        }
    }

    private UIThreadHandler uiThreadHandler;

    @Override
    protected void onStart()
    {
        super.onStart();
        Log.d(TAG, "onStart...");

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK)
        {
            if (requestCode == Declarations.REQUEST_CASH_TOP_UP)
            {
                double cashTopUpAmount = data.getDoubleExtra("CASH_TOPUP_AMOUNT", 0);
                if (cashTopUpAmount > 0)
                {
                    //doPayCashAndTopUp(cashTopUpAmount);
                    DoCheckInAsync xTask = new DoCheckInAsync(
                            CheckInV2Stage.this,
                            progress,
                            DoCheckInAsync.CHECK_IN_BY_CASH_TOP_UP
                    );
                    xTask.execute(cashTopUpAmount);
                }
            }
            else if (requestCode == Declarations.REQUEST_REQUIRED_TOP_UP)
            {
                double topUpAmount = data.getDoubleExtra("TOP_UP_AMOUNT_RESULT", 0);
                if (topUpAmount > 0)
                {
                    if (AddTopUpTransaction(topUpAmount))
                    {
                        WorkingSession.getInstance().ShowToast(
                                CheckInV2Stage.this,
                                "Add Top Up transaction successful",
                                Toast.LENGTH_SHORT
                                                              );

                        //doTapIn();
                        DoCheckInAsync xTask = new DoCheckInAsync(
                                CheckInV2Stage.this,
                                progress,
                                DoCheckInAsync.CHECK_IN_BY_TAP_IN
                        );
                        xTask.execute();
                    }
                }
            }
            else if (requestCode == Declarations.REQUEST_CHECK_IN_STAGE_MORE)
            {
                int xStageCount = data.getIntExtra("SELECTED_STAGE", 0);
                if (xStageCount >= 1 && xStageCount <= 6)
                {
                    int id = Utilities.getResId("checkin_stage_" + xStageCount,
                                                CheckInV2Stage.this,
                                                R.id.class);
                    if (id > -1)
                        ((Button) findViewById(id)).performClick();
                }
                else
                {
                    GetFareV2(xStageCount);
                    CalcTotalAmount();
                }
            }
        }
    }

    private boolean AddTopUpTransaction(double amount)
    {
        //--create top up transaction
        TransactionValue trans = WorkingSession.getInstance().CreateTransaction(
                CheckInV2Stage.this,
                "TOP-UP",
                "Cash",
                0,
                0, 0,
                amount,
                null, //voucher
                null, null,
                0,
                0, 0, 0, 0, 0, 0,
                null,
                ";;;;;");
        if (trans == null)
        {
            WorkingSession.getInstance().ShowErrorDialog(
                    CheckInV2Stage.this,
                    "Create Transaction Error",
                    "System Error.\nCould not create transaction, please contact your administrator."
                                                        );

            return false;
        }
        try
        {
            long rx = db.addTransaction(trans);
            trans.ISN = (int) rx;
        }
        catch (Exception ex)
        {
            WorkingSession.getInstance().ShowErrorDialog(
                    CheckInV2Stage.this,
                    "Create Transaction Error",
                    "System Error.\nCould not create transaction, please contact your administrator."
                                                        );

            return false;
        }
        //--update passenger balance
        WorkingSession.getInstance().currentPassenger.CurrentBalance += trans.TopUpAmount;
        int x = db.updateMemberBalance(
                WorkingSession.getInstance().currentPassenger.ISN,
                WorkingSession.getInstance().currentPassenger.CurrentBalance);

        return true;
    }

    private int InputValidate(int paymentType)
    {
        int inputValidateResult = 1;

        if (currentLocation == null)
        {
            WorkingSession.getInstance().ShowErrorDialog(
                    CheckInV2Stage.this,
                    "Error",
                    "Please select current location");

            inputValidateResult = 0;
        }
        else if (passengerCount <= 0)
        {
            WorkingSession.getInstance().ShowErrorDialog(
                    CheckInV2Stage.this,
                    "Error",
                    "Please choose passenger type \n(Adult, Senior, Child, Disabled, Exempt or Student)"
                                                        );

            inputValidateResult = 0;
        }
        else if (paymentType == 0 &&//BMF
                WorkingSession.getInstance().currentPassenger.CurrentBalance < Amount)
        {
            WorkingSession.getInstance().ShowErrorDialog(
                    CheckInV2Stage.this,
                    "Error",
                    "Customer is not enough balance for check-in"
                                                        );

            inputValidateResult = 0;
        }

        return inputValidateResult;
    }

    OnClickListener onPaybyBMF = new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            String file2Play = "";
            File mp3File = new File(Environment.getExternalStorageDirectory() +
                                            Declarations.ShortHaul_sdCard_Folder + file2Play);

            //--
            if (WorkingSession.getInstance().IsSmartCardTapped())
            {
                if (InputValidate(0) != 1) //not validate or waiting for confirm
                    return;

                file2Play = "process-complete.mp3";

                DoCheckInAsync xTask = new DoCheckInAsync(
                        CheckInV2Stage.this,
                        progress,
                        DoCheckInAsync.CHECK_IN_BY_BMF
                );
                xTask.execute();
            }
            else
            {
                file2Play = "process-error.mp3";
                WorkingSession.getInstance().ShowErrorDialog(CheckInV2Stage.this, "Error!", "Please, insert your card into Card Reader");
            }
            if (!mp3File.exists())
            {
                errorVoice = null;
                WorkingSession.getInstance().ShowToast(
                        CheckInV2Stage.this,
                        "File not found. " + mp3File.getAbsolutePath(),
                        Toast.LENGTH_SHORT
                                                      );
            }
            else
            {
                errorVoice = Utilities.PlayMedia(
                        CheckInV2Stage.this,
                        file2Play);
            }
        }
        //SetAllButtonState(false);
        //doPayByBMF();
        //SetAllButtonState(true);


    };

///---------------------------- test ----------------------------

/// ----------------------------------test ---------------------------

    OnClickListener onCashAndTopUpClick = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            //--
            if (InputValidate(2) < 0) //not validate or waiting for confirm
                return;

            Intent input = new Intent(CheckInV2Stage.this, Cash_TopUp.class);
            input.putExtra("FARE_AMOUNT", Amount);
            startActivityForResult(input, Declarations.REQUEST_CASH_TOP_UP); //will be continued at onActivityResult
        }
    };
    //======================================================================================================================
    private int flag;

    private final class ThreadHandlerCheckCardIntoCardReader extends Handler
    {
        private final String TAG = "ThreadHandlerCheckCardIntoCardReader";

        public ThreadHandlerCheckCardIntoCardReader(Looper lp)
        {
            super(lp);
        }

        //public ThreadHandlerTapCard(){
        //   super();
        //}
        //Intent input = new Intent(Main.this, CheckInV2Stage.class);
        String LogicalNumber = "";

        @Override
        public void handleMessage(final Message msg)
        {
            //super.handleMessage(msg);

            switch (msg.arg1)
            {
                case 1:
                    flag = 1;
                    break;

                case 0:
                    flag = 0;

                    break;
            }
        }

        // TO DO SOMETHINGS AT HERE
        public Message CreateShowToastMsg(String str)
        {
            Message msgTemp = new Message();

            return msgTemp;
        }

        // TO DO SOMETHINGS AT HERE
        public Message CreateShowAlertDialogMsg(String dialogTitle, String content)
        {
            Message mgs = new Message();

            return mgs;
        }
    }

    //====================================================================================================================
    private void GetFareV2(int xStageCount)
    {
        if (stageCount == 0) //tap out
        {
            int xCount = db.getStageCountOfRoute(WorkingSession.getInstance().journalRoute.ISN);
            xStageFare = db.getStageFare(WorkingSession.getInstance().journalRoute.ISN, xCount);
            stageCount = xCount;
        }
        else
        {
            xStageFare = db.getStageFare(WorkingSession.getInstance().journalRoute.ISN, xStageCount);
            stageCount = xStageCount;
        }

        if (xStageFare < 0)
        {
            WorkingSession.getInstance().ShowToast(CheckInV2Stage.this,
                                                   "Could not get fare of Stage " + xStageCount,
                                                   Toast.LENGTH_SHORT);
            xStageFare = 0;
        }
    }

    private TransactionValue CreateTransaction(String type, double topUpAmount, VoucherValue vv, boolean updateBalance)
    {
        TransactionValue trans = null;
        try
        {
            //---
            int adultCount = getPassengerCount(adult);
            int seniorCount = getPassengerCount(senior);
            int childCount = getPassengerCount(child);
            int disabledCount = getPassengerCount(disabled);
            //int exemptCount = getPassengerCount(exempt);
            int studentCount = getPassengerCount(student);

            String description = String.format("Check-in near %s",
                                               currentLocation.StationName);
			/*if (checkinType != Declarations.CHECK_IN_TYPE_TAP_IN)
				description += String.format(" for %d stages. ", stageCount);
			else
				description += "[@checkout]. ";*/
            description += String.format(" for %d stages. ", stageCount);

            if (adultCount > 0)
                description += String.format("Adult: %d,", adultCount);
            if (seniorCount > 0)
                description += String.format(" Senior: %d,", seniorCount);
            if (childCount > 0)
                description += String.format(" Child: %d,", childCount);
            if (disabledCount > 0)
                description += String.format(" Disabled: %d,", disabledCount);
            /*if (exemptCount > 0)
                description += String.format(" Exempt: %d,", exemptCount);*/
            if (studentCount > 0)
                description += String.format(" Student: %d,", studentCount);

            description = description.substring(0, description.length() - 1);

            trans = WorkingSession.getInstance().CreateTransaction(
                    CheckInV2Stage.this,
                    "CHECK-IN",
                    type,
                    Amount,
                    0, //freight
                    0,//ExcessiveBag
                    topUpAmount,
                    vv,
                    currentLocation,
                    null,
                    xStageFare,
                    adultCount,
                    seniorCount,
                    childCount,
                    disabledCount,
                    0, //exemptCount,
                    studentCount,
                    null,
                    description
                                                                  );
            //--
            if (trans == null)
            {
                Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator. [1]"
                                                                        );
                uiThreadHandler.sendMessage(error);

                /*WorkingSession.getInstance().ShowErrorDialog(
                        CheckInV2Stage.this,
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator."
                );*/
                return null;
            }

			/*if (checkinType == Declarations.CHECK_IN_TYPE_NO_CARD ||
					checkinType == Declarations.CHECK_IN_TYPE_NORMAL)
			{
				trans.CheckOutDate = new Date();
			}*/
            trans.CheckOutDate = new Date();

            try
            {
                long rx = db.addTransaction(trans);
                trans.ISN = (int) rx;
            }
            catch (Exception ex)
            {
                Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator. [2]"
                                                                        );
                uiThreadHandler.sendMessage(error);

                /*WorkingSession.getInstance().ShowErrorDialog(
                        CheckInV2Stage.this,
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator."
                );*/
                return null;
            }

            if (trans.ISN == 0)
            {
                Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator. [3]"
                                                                        );
                uiThreadHandler.sendMessage(error);

                /*WorkingSession.getInstance().ShowErrorDialog(
                        CheckInV2Stage.this,
                        "Create Transaction Error",
                        "System Error.\nCould not create transaction, please contact your administrator."
                );*/
                return null;
            }

            //---
            ///-- add check-in to card
            WaitCardReaderOpenAndTapped();

            if (WorkingSession.getInstance().IsSmartCardTapped())
            {
                NfcCardInfo x = WorkingSession.getInstance().SAMCheckIn(
                        WorkingSession.getInstance().getLastTappedCardType(),
                        (float) currentLocation.Latitude,
                        (float) currentLocation.Longitude,
                        0,
                        0
                                                                       );
                if (x != null)
                    Log.d(TAG, "[CreateTransaction] Write check-in to card successful.");
                else
                    Log.d(TAG, "[CreateTransaction] Unable to write check-in to card.");

                x = WorkingSession.getInstance().SAMCheckOut(
                        WorkingSession.getInstance().getLastTappedCardType(),
                        (int) (Amount * 100),
                        (float) currentLocation.Latitude,
                        (float) currentLocation.Longitude,
                        0,
                        0
                                                            );
                if (x != null)
                    Log.d(TAG, "[CreateTransaction] Write check-out to card successful.");
                else
                    Log.d(TAG, "[CreateTransaction] Unable to write check-out to card.");
            }

            //WorkingSession.getInstance().ShowToast(CheckInV2Stage.this, "Add transaction successful", Toast.LENGTH_SHORT);
            Message msg = uiThreadHandler.CreateShowToastMsg("Add transaction successful");
            uiThreadHandler.sendMessage(msg);
            //--
            if (updateBalance)
            {
                WorkingSession.getInstance().currentPassenger.CurrentBalance += trans.TopUpAmount - trans.FareAmount;
                int x = db.updateMemberBalance(
                        WorkingSession.getInstance().currentPassenger.ISN,
                        WorkingSession.getInstance().currentPassenger.CurrentBalance);
                if (x > 0)
                {

                    msg = uiThreadHandler.CreateShowToastMsg("Update customer balance successful");
                    uiThreadHandler.sendMessage(msg);
                    /*WorkingSession.getInstance().ShowToast(CheckInV2Stage.this,
                            "Update customer balance successful", Toast.LENGTH_SHORT);*/
                }
                else
                {
                    msg = uiThreadHandler.CreateShowToastMsg("Update customer balance failed");
                    uiThreadHandler.sendMessage(msg);
                    /*WorkingSession.getInstance().ShowToast(CheckInV2Stage.this,
                            "Update customer balance failed", Toast.LENGTH_SHORT);*/
                }
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

        return trans;
    }

    private boolean WaitCardReaderOpenAndTapped()
    {
//        if (WorkingSession.getInstance().getSAM_NfcCardTapped() == -1)
//            WorkingSession.getInstance().OpenSAMCardReader(-1); //open with last information
        Log.d(TAG, "[WaitCardReaderOpenAndTapped] Waiting for card tapped in 10s");
        Date lastTest = new Date();
        long diffInSec = 0;
        try
        {
            do
            {
                Thread.sleep(200);
                long diffInMs = (new Date()).getTime() - lastTest.getTime();
                diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);
                lastTest = new Date();
            }
            while (!WorkingSession.getInstance().IsSmartCardTapped() && diffInSec < 10); //waiting for 10s


        }
        catch (Exception ex)
        {
            Log.e(TAG, "[WaitCardReaderOpenAndTapped] Exception: " + ex);
            ex.printStackTrace();
            return false;
        }

        if (diffInSec >= 10)
            return false;
        return true;
    }

    private String CreateReceiptContent(TransactionValue xx)
    {
        Date date = new Date();
        String receiptDate = Utilities.DateToString(date, "dd/MM/yyyy");
        String receiptTime = Utilities.DateToString(date, "hh:mm a");

        String content = Utilities.StringAlignCenter(48, "BulaMy(Fiji) - BMF etikite  ") //+ "\n"
                + Utilities.StringAlignCenter(48, "BMF Make It Your Choice")
                + Utilities.StringAlignCenter(48, "www.bulamyfiji.com")
                + "\n\n"
                + Utilities.StringAlignLeftRight(48,
                                                 "Entry: " + currentLocation.StationName,
                                                 "Bus Reg.: " + WorkingSession.getInstance().journalBus.BusNumber
                                                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                                                 "Stages: " + stageCount,
                                                 "Driver: " + WorkingSession.getInstance().journalDriver.FullName
                                                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                                                 "No. PAX: " + String.valueOf(passengerCount),
                                                 "Company: DeeCees Fiji Ltd"
                                                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                                                 "Fare: " + WorkingSession.getInstance().decimalFormat.format(xStageFare),
                                                 "TIN: 12683467161"
                                                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                                                 "Total: " + String.valueOf(WorkingSession.getInstance().RoundMoney(Amount)),
                                                 "Issued: " + receiptDate + " " + receiptTime
                                                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                                                 "ACCT Name: " + WorkingSession.getInstance().currentPassenger.getFullName(),
                                                 "Mode: " + xx.Type
                                                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                                                 "ACCT #: " + WorkingSession.getInstance().currentPassenger.CardNumber,
                                                 "TopUp Amount: " + WorkingSession.getInstance().decimalFormat.format(xx.TopUpAmount)
                                                ) + "\n"
                + Utilities.StringAlignLeftRight(48,
                                                 "Balance: " + WorkingSession.getInstance().decimalFormat.format(
                                                         WorkingSession.getInstance().currentPassenger.CurrentBalance),
                                                 "Transaction ID: " + xx.TransactionID
                                                ) + "\n"
                + "\nPlease Keep Receipt For Your Records\n\n";

        return content;
    }

    private boolean PrintReceipt(TransactionValue xx)
    {
		/*String x = db.getRuntimeValues("print-receipt");
		if(x == null || x.length() == 0)
			x = "1";
		if(x.equals("0"))
			return false;*/
        if (!WorkingSession.getInstance().printReceipt)
            return false;
        //--
        String receipt = CreateReceiptContent(xx);

        int rs = WorkingSession.getInstance().PreparePrintReceiptWifi(CheckInV2Stage.this, receipt, printReceiptCallback);

        if (rs == Declarations.NO_WIFI_PRINTER_SETUP)
        {
            /*runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    WorkingSession.getInstance().ShowToast(CheckInV2Stage.this, "No printer selected. Please setup one.", Toast.LENGTH_LONG);
                }
            });*/

            Message error = uiThreadHandler.CreateShowToastMsg(
                    "No printer selected. Please setup one.");
            uiThreadHandler.sendMessage(error);

            /*Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                    "Print Receipt Error",
                    "No printer selected. Please setup one.");
            uiThreadHandler.sendMessage(error);*/

            //WorkingSession.getInstance().ShowToast(CheckInV2Stage.this, "No printer selected. Please setup one.", Toast.LENGTH_LONG);
        }
        else if (rs == Declarations.PRINT_RECEIPT_ERROR)
        {
            /*runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    WorkingSession.getInstance().ShowToast(CheckInV2Stage.this, "Print receipt failed.", Toast.LENGTH_LONG);
                }
            });*/

            Message error = uiThreadHandler.CreateShowToastMsg(
                    "Print receipt failed.");
            uiThreadHandler.sendMessage(error);

            //WorkingSession.getInstance().ShowToast(CheckInV2Stage.this, "Print receipt failed.", Toast.LENGTH_LONG);
        }
        return rs == Declarations.PRINT_RECEIPT_WAITING;
    }

    private final Handler printReceiptCallback = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            Message error = null;
            switch (msg.what)
            {
                case Declarations.WIFI_PRINTER_CONNECTED:
                    WorkingSession.getInstance().ShowToast(CheckInV2Stage.this,
                                                           "Printer connected", Toast.LENGTH_SHORT);
                    WorkingSession.getInstance().PrintReceipt();
                    break;
                case Declarations.WIFI_PRINTER_CONNECTED_ERR:
                    Log.d(TAG, String.format(
                                  "WIFI_PRINTER_CONNECTED_ERR. Unable connect to printer %s",
                                  WorkingSession.getInstance().wifiPrinterAddress)
                         );
                    /*WorkingSession.getInstance().ShowToast(CheckInV2Stage.this,
                            "Unable connect to printer", Toast.LENGTH_SHORT);*/
                    progress.dismiss();
                    //--
                    AlertDialog.Builder dialog = new AlertDialog.Builder(CheckInV2Stage.this);
                    dialog.setNegativeButton("OK", new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            uiThreadHandler.sendEmptyMessage(UIThreadHandler.DO_BACK_PRESS);
                        }
                    });
                    AlertDialog alert = dialog.create();
                    alert.setTitle("Print Receipt Error");
                    alert.setMessage(
                            String.format("Unable connect to printer %s",
                                          WorkingSession.getInstance().wifiPrinterAddress)
                                    );
                    //--
                    alert.show();
                    //--
                    break;
                case Declarations.WIFI_PRINTER_SEND_FAILED:
                    error = uiThreadHandler.CreateShowToastMsg(
                            "Unable send data to printer.");
                    uiThreadHandler.sendMessage(error);

                    /*WorkingSession.getInstance().ShowToast(CheckInV2Stage.this,
                            "Unable send data to printer", Toast.LENGTH_SHORT);*/
                    break;
                case Declarations.PRINT_RECEIPT_SUCCESSFUL:
                    error = uiThreadHandler.CreateShowToastMsg(
                            "Print receipt successful.");
                    uiThreadHandler.sendMessage(error);
                    /*WorkingSession.getInstance().ShowToast(CheckInV2Stage.this,
                            "Print receipt successful", Toast.LENGTH_SHORT);*/
                    //onBackPressed();
                    uiThreadHandler.sendEmptyMessage(UIThreadHandler.DO_BACK_PRESS);
                    break;
            }
        }
    };

    // private MediaPlayer errorVoice;
    private void doPayByBMF()
    {
        try
        {
            TransactionValue trans = CreateTransaction("BMF", 0, null, true);
            if (trans == null)
                return;
            //-------------------TEST-------------------
            WorkingSession.getInstance().transactionCount++;
            //-------------------TEST-------------------


            if (!PrintReceipt(trans))
            {
                uiThreadHandler.sendEmptyMessage(UIThreadHandler.DO_BACK_PRESS);
                //onBackPressed();
            }
        }
        catch (Exception ex)
        {
            Log.e(TAG, "doPayByBMF: " + ex.getMessage());
            Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                    "System Error",
                    ex.getMessage()
                                                                    );
            uiThreadHandler.sendMessage(error);

            /*WorkingSession.getInstance().ShowErrorDialog(
                    CheckInV2Stage.this,
                    "System Error",
                    ex.getMessage());*/
        }
    }

    private void doPayByCash()
    {
        try
        {
            TransactionValue trans = CreateTransaction("Cash", 0, null, false);

            //-------------------TEST-------------------
            WorkingSession.getInstance().transactionCount++;
            //-------------------TEST-------------------
            if (!PrintReceipt(trans))
            {
                uiThreadHandler.sendEmptyMessage(UIThreadHandler.DO_BACK_PRESS);
                //onBackPressed();
            }
        }
        catch (Exception ex)
        {
            Log.e(TAG, "doPayByCash: " + ex.getMessage());
            Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                    "System Error",
                    ex.getMessage()
                                                                    );
            uiThreadHandler.sendMessage(error);
            /*WorkingSession.getInstance().ShowErrorDialog(
                    CheckInV2Stage.this,
                    "System Error",
                    ex.getMessage());*/
        }
    }

    //this function is called in onActivityResult
    private void doPayCashAndTopUp(double inputAmount)
    {
        try
        {
            TransactionValue trans = CreateTransaction("Cash-TopUp", inputAmount, null, true);

            //-------------------TEST-------------------
            WorkingSession.getInstance().transactionCount++;
            //-------------------TEST-------------------
            if (!PrintReceipt(trans))
            {
                uiThreadHandler.sendEmptyMessage(UIThreadHandler.DO_BACK_PRESS);
                //onBackPressed();
            }
        }
        catch (Exception ex)
        {
            Log.e(TAG, "doPayCashAndTopUp: " + ex.getMessage());
            Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                    "System Error",
                    ex.getMessage()
                                                                    );
            uiThreadHandler.sendMessage(error);
            /*WorkingSession.getInstance().ShowToast(CheckInV2Stage.this, ex.getMessage(),
                    Toast.LENGTH_LONG);*/
        }
    }

    //this function is called in onActivityResult
    private void doPayByStudentVoucher(
            String voucherType, double discountAmount,
            int collectBalanceType, double collectAmount)
    {
        try
        {
            VoucherValue vv = new VoucherValue();
            vv.VoucherType = voucherType;
            vv.VoucherAmount = discountAmount;

            TransactionValue trans = null;
            if (collectBalanceType == StudentVoucher.COMPLETE_PAYMENT_BY_VOUCHER)
            {
                trans = CreateTransaction(
                        "Student-Voucher",
                        0,
                        vv,
                        false);
            }
            else if (collectBalanceType == StudentVoucher.COMPLETE_PAYMENT_BY_BMF)
            {
                trans = CreateTransaction(
                        "BMF",
                        0,
                        vv,
                        false);
            }
            else if (collectBalanceType == StudentVoucher.COMPLETE_PAYMENT_BY_CASH)
            {
                trans = CreateTransaction(
                        "Cash",
                        collectAmount,
                        vv,
                        false);
            }
            if (trans == null)
            {
                WorkingSession.getInstance().ShowErrorDialog(
                        CheckInV2Stage.this,
                        "Error",
                        "System Error.\nCould not add Transaction"
                                                            );
                return;
            }
            //-------------------TEST-------------------
            WorkingSession.getInstance().transactionCount++;
            //-------------------TEST-------------------
            if (!PrintReceipt(trans))
            {
                uiThreadHandler.sendEmptyMessage(UIThreadHandler.DO_BACK_PRESS);
                //onBackPressed();
            }
        }
        catch (Exception ex)
        {
            Log.e(TAG, "doPayByStudentVoucher: " + ex.getMessage());
            Message error = uiThreadHandler.CreateShowAlertDialogMsg(
                    "System Error",
                    ex.getMessage()
                                                                    );
            uiThreadHandler.sendMessage(error);

            /*WorkingSession.getInstance().ShowToast(CheckInV2Stage.this, ex.getMessage(),
                    Toast.LENGTH_LONG);*/
        }
    }

    OnClickListener onCancelClick = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

            onBackPressed();
        }
    };

	/*OnClickListener onSubmitClick = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			if (InputValidate(0) == 0) //not validate or waiting for confirm
				return;
			else if (InputValidate(0) == 2) //Top up required
			{
				Intent runActivity = new Intent(CheckInV2Stage.this, checkin_topup.class);
				runActivity.putExtra("REQUIRED_FARE_AMOUNT", minFare);
				startActivityForResult(runActivity, Declarations.REQUEST_REQUIRED_TOP_UP);
				return;
			}


            *//*if(v == null)
                processing = true;
            else
                SetAllButtonState(false);
            //--
            doTapIn();
            //--
            if(v == null)
                processing = false;
            else
                SetAllButtonState(true);*//*
			DoCheckInAsync xTask = new DoCheckInAsync(
					CheckInV2Stage.this,
					progress,
					DoCheckInAsync.CHECK_IN_BY_TAP_IN
			);
			xTask.execute();
		}
	};*/

    private void doTapIn()
    {
        try
        {
            TransactionValue trans = CreateTransaction("BMF", 0, null, false);
            if (trans == null)
                return;
            // go back to Home
            uiThreadHandler.sendEmptyMessage(UIThreadHandler.DO_BACK_PRESS);
            //onBackPressed();
        }
        catch (Exception ex)
        {
            WorkingSession.getInstance().ShowErrorDialog(
                    CheckInV2Stage.this,
                    "System Error",
                    ex.getMessage());
        }
    }

    private boolean processing = false;
    //int oldState = 0;

    @Override
    public void onBackPressed()
    {
        try
        {
            progress.dismiss();
        }
        catch (Exception ex)
        {
            Log.e(TAG, "[onBackPress] " + ex.toString());
        }
        //--
        Intent next = new Intent(CheckInV2Stage.this, Main.class);

        next.putExtra("INPUT_DIRECT_CHECK_IN", 0);
        if (Main.getInstance() != null)
            Main.getInstance().setIntent(next);

        //super.onBackPressed();
        finish();
    }

//	@Override
//	public void onNewIntent(Intent intent)
//	{
//		String action = intent.getAction();
//		Log.d(TAG, String.format("[onNewIntent] Action: %s", action));
//
//		if (action != null && (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)
//				|| action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
//				&& !processing)
//		{
//			String[] result = Utilities.readNFCTagContentAndSerial(CheckInV2Stage.this, intent);
//			//--result[0] = TagSerial, result[1] = Tag content
//			if (result == null || result.length < 2)
//				return;
//
//			if (result[1].length() == 0)
//			{
//				WorkingSession.getInstance().ShowErrorDialog(
//						CheckInV2Stage.this,
//						"Error",
//						"Invalid NFC Tag Content"
//				);
//				return;
//			}
//
//			MemberValue member = db.getMemberByCard(result[1], result[0]);
//
//			if (member != null)
//			{
//				// go back to Home
//				Intent mainScreen = new Intent(CheckInV2Stage.this, Main.class);
//				mainScreen.putExtra("INPUT_CUSTOMER", member.CardNumber);
//				//startActivity(mainScreen);
//
//				if(Main.getInstance() != null)
//					Main.getInstance().setIntent(mainScreen);
//				finish();
//			}
//			else
//			{
//				//Utilities.PlayMedia(CheckInV2Stage.this, "C.mp3");
//				WorkingSession.getInstance().ShowErrorDialog(
//						CheckInV2Stage.this,
//						"Error",
//						"Could not get customer of Card#: " + result[1]
//				);
//			}
//		}
//		else
//		{
//			Log.d(TAG, "Action: " + action + ", on processing current task");
//		}
//	}

    @Override
    protected void onResume()
    {
        Log.d(TAG, "[onResume] ....");
        super.onResume();
//		if (nfcAdapter != null)
//		{
//			nfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
//			// mAdapter.enableForegroundNdefPush(this);
//		}
    }

    @Override
    protected void onPause()
    {
        Log.d(TAG, "[onPause] ....");
        super.onPause();
//		if (nfcAdapter != null)
//		{
//			nfcAdapter.disableForegroundDispatch(this);
//			//nfcAdapter.disableForegroundNdefPush(this);
//			nfcAdapter.setNdefPushMessage(null, this);
//		}
		/*if (autoSubmit != null)
			autoSubmit.cancel();*/
        if (errorVoice != null)
            errorVoice.stop();
        //WorkingSession.getInstance().CancelShowingToast();
    }

    @Override
    protected void onDestroy()
    {
        Log.d(TAG, "[onDestroy] ....");
        super.onDestroy();
		/*if (autoSubmit != null)
			autoSubmit.cancel();*/
        if (errorVoice != null)
            errorVoice.stop();
    }

    private int lastCheckId = 0;
    private RadioGroup.OnCheckedChangeListener onPassengerCheckedChange = new RadioGroup.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i)
        {
            Log.d(TAG, "[onPassengerCheckedChange] id: " + i);

            if (i == -1)
                return;
            //--
            if (i == lastCheckId)
                return;
            //--
            lastCheckId = i;
            //--
            if (!((RadioButton) findViewById(i)).isChecked())
                return;

            CalcTotalAmount();
            //--
            String selectText = ((RadioButton) findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();

            if (selectText.equals("0"))
                return;
        }
    };

    private final class UIThreadHandler extends Handler
    {
        private final String TAG = "CheckInUIThreadHandler";
        public static final int MSG_COUNT_DOWN = 0x10;
        public static final int SHOW_TOAST = 0x11;
        public static final int SHOW_ALERT_DIALOG = 0x12;
        public static final int DO_CHECK_IN_BY_CASH = 0x13;
        public static final int DO_BACK_PRESS = 0x14;
        private int currentCountDownValue = Declarations.TAP_IN_TIMEOUT_SECONDS;


        public UIThreadHandler(Looper lp)
        {
            super(lp);
        }

        @Override
        public void handleMessage(Message msg)
        {
            try
            {
                switch (msg.what)
                {
                    case UIThreadHandler.SHOW_TOAST:
                    {
                        String content = msg.getData().getString("TOAST_CONTENT", "");
                        if (content.length() == 0)
                            break;
                        WorkingSession.getInstance().ShowToast(
                                CheckInV2Stage.this,
                                content,
                                Toast.LENGTH_SHORT);
                        break;
                    }
                    case UIThreadHandler.SHOW_ALERT_DIALOG:
                    {
                        String title = msg.getData().getString("DIALOG_TITLE", "");
                        String content = msg.getData().getString("DIALOG_CONTENT", "");
                        if (content.length() == 0)
                            break;
                        WorkingSession.getInstance().ShowErrorDialog(
                                CheckInV2Stage.this,
                                title,
                                content);
                        break;
                    }
                    case DO_CHECK_IN_BY_CASH:
                    {
                        Thread.sleep(500);
                        Log.d(TAG, "Do Check-in by cash");
                        //--
                        DoCheckInAsync xTask = new DoCheckInAsync(
                                CheckInV2Stage.this,
                                progress,
                                DoCheckInAsync.CHECK_IN_BY_CASH
                        );
                        xTask.execute();
                        //--
                        break;
                    }
                    case DO_BACK_PRESS:
                        Thread.sleep(500);
                        runOnUiThread(new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                onBackPressed();
                            }
                        });
                }
            }
            catch (Exception ex)
            {
                Log.e(TAG, String.format("[MSG:%d] %s", msg.what, ex.getMessage()));
            }
        }

        public Message CreateShowToastMsg(String content)
        {
            Message msg = new Message();
            msg.what = SHOW_TOAST;

            Bundle data = new Bundle();
            data.putString("TOAST_CONTENT", content);
            msg.setData(data);

            return msg;
        }

        public Message CreateShowAlertDialogMsg(String dialogTitle, String content)
        {
            Message msg = new Message();
            msg.what = SHOW_ALERT_DIALOG;

            Bundle data = new Bundle();
            data.putString("DIALOG_TITLE", dialogTitle);
            data.putString("DIALOG_CONTENT", content);
            msg.setData(data);

            return msg;
        }
    }

    public class DoCheckInAsync extends AsyncTask<Object, Void, Void>
    {
        public static final int CHECK_IN_BY_BMF = 1000;
        public static final int CHECK_IN_BY_CASH = 1001;
        public static final int CHECK_IN_BY_CASH_TOP_UP = 1002;
        public static final int CHECK_IN_BY_STUDENT_VOUCHER = 1003;
        public static final int CHECK_IN_BY_TAP_IN = 1004;

        private ProgressDialog progress;
        private Context callerContext;
        private int checkInType;

        public DoCheckInAsync(Context context, ProgressDialog dialog, int checkInType)
        {
            callerContext = context;
            progress = dialog;
            this.checkInType = checkInType;
        }

        public void onPreExecute()
        {
            Log.d(TAG, "[DoCheckInAsync.onPreExecute] ...");
            processing = true;
            progress.show();
            //--
            super.onPreExecute();
        }

        public Void doInBackground(Object... inputValues)
        {
            try
            {
                Log.d(TAG, "[DoCheckInAsync.doInBackground] ...");
                switch (this.checkInType)
                {
                    case CHECK_IN_BY_CASH:
                        doPayByCash();
                        break;
                    case CHECK_IN_BY_BMF:
                        doPayByBMF();
                        break;
                    case CHECK_IN_BY_TAP_IN:
                        doTapIn();
                        break;
                    case CHECK_IN_BY_CASH_TOP_UP:
                        doPayCashAndTopUp(((Number) inputValues[0]).doubleValue());
                        break;
                    case CHECK_IN_BY_STUDENT_VOUCHER:
                        doPayByStudentVoucher(
                                String.valueOf(inputValues[0]), //voucherType
                                ((Number) inputValues[1]).doubleValue(), //discountAmount
                                ((Number) inputValues[2]).intValue(), //collectBalanceType
                                ((Number) inputValues[3]).doubleValue() //collectAmount
                                             );
                }
            }
            catch (Exception ex)
            {
                Log.e(TAG, "[DoCheckInAsync.doInBackground] " + ex.getMessage());
            }

            return null;
        }

        public void onPostExecute(Void unused)
        {
            Log.d(TAG, "[DoCheckInAsync.onPostExecute] ...");
            processing = false;
            super.onPostExecute(unused);
        }
    }

}
